package com.ruix.app.ui.stratum.lesson;

import android.app.Activity;
import android.content.Intent;
import android.text.TextUtils;
import android.view.View;

import com.hyphenate.chat.EMMessage;
import com.hyphenate.easeui.ui.EaseChatFragment;
import com.hyphenate.easeui.widget.chatrow.EaseCustomChatRowProvider;
import com.ruix.app.R;
import com.ruix.app.manager.UserManager;
import com.ruix.app.model.User;
import com.ruix.app.network.RXObserver;
import com.ruix.app.network.RequestFactory;
import com.ruix.app.util.LogUitl;
import com.ruix.app.util.ToastUtil;
import com.ruix.app.widget.dialog.CommonDialog;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import io.reactivex.disposables.Disposable;
import me.iwf.photopicker.PhotoPicker;

/**
 * Created by hadexs on 2017/5/18.
 */

public class ChatFragment extends EaseChatFragment implements EaseChatFragment.EaseChatFragmentHelper {


    protected static final int REQUEST_CODE_QUESTION = 1000;
    protected static final int REQUEST_CODE_CLEAR_TARGET = 2000;
    protected static final int REQUEST_CODE_SUMUP = 30000;
    protected static final int REQUEST_CODE_LOCAL = 3;


    protected static final int REQUEST_ALL_SEND = 1;
    protected static final int REQUEST_CLEAR_QUSTION = 2;
    protected static final int REQUEST_SHARE = 3;
    protected static final int REQUEST_GET_QUSTION = 4;
    protected static final int REQUEST_SEN_TOTAL = 5;
    protected static final int REQUEST_SEND_PIC = 6;
    private boolean clearTarget;
    private boolean outQuesttion;
    private boolean shareAction;
    private boolean sumupAction;
    private boolean munteAction;
    private boolean unmuteAction;
    private boolean mute; //禁言状态
    private ArrayList<String> selectedPhotos = new ArrayList<>();

    protected int[] itemShitStrings = { R.string.lesson_input_other_one_shit, R.string.lesson_input_other_two, R.string.lesson_input_other_four,R.string.lesson_input_other_three ,R.string.lesson_input_other_five,R.string.lesson_input_other_six};
    protected int[] itemShitdrawables = { R.drawable.input_other_one_unenable, R.drawable.input_other_two,R.drawable.input_other_four,R.drawable.input_other_three,R.drawable.input_other_five,R.drawable.input_other_six };


    protected int[] itemStrings = { R.string.lesson_input_other_one, R.string.lesson_input_other_two, R.string.lesson_input_other_four,R.string.lesson_input_other_three ,R.string.lesson_input_other_five,R.string.lesson_input_other_six};
    protected int[] itemdrawables = { R.drawable.input_other_one, R.drawable.input_other_two,R.drawable.input_other_four,R.drawable.input_other_three,R.drawable.input_other_five,R.drawable.input_other_six };
    protected int[] itemSIds = { REQUEST_ALL_SEND, REQUEST_CLEAR_QUSTION,REQUEST_SHARE, REQUEST_GET_QUSTION,REQUEST_SEN_TOTAL,REQUEST_SEND_PIC };
    //EaseChatExtendMenu

    protected int[] itemStudenStrings = { R.string.lesson_input_other_six};
    protected int[] itemStudendrawables = { R.drawable.input_other_six };
    protected int[] itemStudenIds = { REQUEST_SEND_PIC };
    //EaseChatExtendMenu

    @Override
    protected void initView() {
        super.initView();
        hideTitleBar();
//        myExtendMenuItemClickListener = new MyExtendMenuItemClickListener();
        setChatFragmentHelper(this);
//        getMuteState();
    }

    protected void registerExtendMenuItem(){
      User currenUser =   UserManager.getCurrentUser();
        if (currenUser.isStudent()){
            for(int i = 0; i < itemStudenStrings.length; i++){
                inputMenu.registerExtendMenuItem(itemStudenStrings[i], itemStudendrawables[i], itemStudenIds[i], extendMenuItemClickListener);
            }
        } else {
            for(int i = 0; i < itemStrings.length; i++){
                inputMenu.registerExtendMenuItem(itemStrings[i], itemdrawables[i], itemSIds[i], extendMenuItemClickListener);
            }
        }
    }

    private void changeExtendMenuItem(){
        if (mute) {
            inputMenu.clearExtendMenuItem();
            for(int i = 0; i < itemStrings.length; i++){
                inputMenu.registerExtendMenuItem(itemStrings[i], itemdrawables[i], itemSIds[i], extendMenuItemClickListener);
            }
//            inputMenu.notifyExtenMenuChanged();
        } else {
            inputMenu.clearExtendMenuItem();
            for (int i = 0; i < itemShitStrings.length; i++) {
                inputMenu.registerExtendMenuItem(itemShitStrings[i], itemShitdrawables[i], itemSIds[i], extendMenuItemClickListener);
            }
//            inputMenu.notifyExtenMenuChanged();
        }
    }




    //发送问题
    private void sendQuestionMessage(String content){
        outQuesttion = true;
        sendTextMessage(content);
        outQuesttion = false;
    }

    //明确目标
    private void sendClearTargeMessage(String content){
        clearTarget = true;
        sendTextMessage(content);
        clearTarget = false;
    }

    //分享
    private void sendShare(){
        shareAction = true;
        sendTextMessage("share");
        shareAction = false;
    }

    //发送问题
    private void sendSumupMessage(String content){
        sumupAction = true;
        sendTextMessage(content);
        sumupAction = false;
    }

    private void sendMudeMessage(String content){
        munteAction = true;
        sendTextMessage(content);
        munteAction = false;
    }

    private void sendunMudeMessage(String content){
        unmuteAction = true;
        sendTextMessage(content);
        unmuteAction = false;
    }





    @Override
    public void onSetMessageAttributes(EMMessage message) {
        if (clearTarget){
            message.setAttribute("type", "target");
        }  else if (outQuesttion){
            message.setAttribute("type", "question");
        } else if (shareAction){
            message.setAttribute("type", "discuss");
        }  else if (sumupAction){
            message.setAttribute("type", "conclusion");
        }  else if (munteAction){
            message.setAttribute("type", "mute");
        } else if (unmuteAction){
            message.setAttribute("type", "unmute");
        } else {
            message.setAttribute("type", "text");
        }
          //// TODO: 2017/5/18
        User user = UserManager.getCurrentUser();
        if (user != null) {
            JSONObject object = new JSONObject();
            try {
                object.put("id", user.getID());
                object.put("name", user.getName());
                object.put("avatar", user.getAvatar());
                object.put("role", user.getRole());
            } catch (JSONException e) {
                e.printStackTrace();
            }
            message.setAttribute("author", object);
        }
    }



    @Override
    public void onEnterToChatDetails() {

    }

    @Override
    public void onAvatarClick(String username) {

    }

    @Override
    public void onAvatarLongClick(String username) {

    }

    @Override
    public boolean onMessageBubbleClick(EMMessage message) {
        return false;
    }

    @Override
    public void onMessageBubbleLongClick(EMMessage message) {

    }

    @Override
    public boolean onExtendMenuItemClick(int itemId, View view) {
        LogUitl.e("id----" + itemId);
        switch (itemId) {
            case REQUEST_ALL_SEND:  //发言和禁止发言
                //todo  发言
                changeExtendMenuItem();
                if (mute){ ////当前禁言
                    sendunMudeMessage("unmute");
//                    setMuteState(true);//解除禁言
                } else {//当前未禁言
                    sendMudeMessage("mute"); //
//                    setMuteState(false);
                }
                //发送禁言消息
//
                break;
            case REQUEST_CLEAR_QUSTION: //明确目标
                getActivity().startActivityForResult(ClearTargetActivity.getInstent(getActivity()),REQUEST_CODE_CLEAR_TARGET);
                break;
            case REQUEST_SHARE: //分享探讨
                showSendShareDialog();
                break;

            case REQUEST_GET_QUSTION: //提出问题
                getActivity().startActivityForResult(AskQuestionActivity.getInstent(getActivity()),REQUEST_CODE_QUESTION);
                break;

            case REQUEST_SEN_TOTAL: //总结
                getActivity().startActivityForResult(LessonSumupActivity.getInstent(getActivity()),REQUEST_CODE_SUMUP);

                break;

            case REQUEST_SEND_PIC: //发布图片
                //权限
                selectPic();
//                selectPicFromCamera();
//                sendFileMessage();
                //// TODO: 2017/5/18
                break;

            default:
                break;
        }

        return true;
    }

    private void selectPic(){
        selectedPhotos.clear();
        PhotoPicker.builder()
                .setPhotoCount(9)
                .setShowCamera(true)
                .setPreviewEnabled(false)
                .setSelected(selectedPhotos)
                .start(getActivity());
    }



    @Override
    public EaseCustomChatRowProvider onSetCustomChatRowProvider() {
        return null;
    }


    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode,resultCode,data);
        if (requestCode == REQUEST_CODE_QUESTION && resultCode == Activity.RESULT_OK){
           String questions =  data.getStringExtra("question");
            if (!TextUtils.isEmpty(questions)){
                sendQuestionMessage(questions);
            }
        } else if (requestCode == REQUEST_CODE_SUMUP && resultCode == Activity.RESULT_OK){
            String questions =  data.getStringExtra("sumup");
            if (!TextUtils.isEmpty(questions)){
                sendSumupMessage(questions);
            }
        } else if (requestCode == REQUEST_CODE_CLEAR_TARGET && resultCode == Activity.RESULT_OK){
            String questions =  data.getStringExtra("clearTarge");
            if (!TextUtils.isEmpty(questions)){
                sendClearTargeMessage(questions);
            }
        } else if (requestCode == PhotoPicker.REQUEST_CODE && resultCode == Activity.RESULT_OK ) {
            List<String> photos = null;
            if (data != null) {
                photos = data.getStringArrayListExtra(PhotoPicker.KEY_SELECTED_PHOTOS);
            }
            if (photos != null) {
                sendImagesMessage(photos);
            }
        }
    }

    private void sendImagesMessage(List<String> photos){
        for (int i = 0; i < photos.size(); i++) {
            sendImageMessage(photos.get(i));
        }
    }

    private void showSendShareDialog(){
        CommonDialog dialog = new CommonDialog(this.getActivity());
        dialog.setListener(new CommonDialog.CommonDialogAcitonListener() {
            @Override
            public void positiveAction() {
                sendShare();
            }

            @Override
            public void negertivieAction() {

            }
        });
        dialog.show("是否要开启分享探讨？");
    }

    @Override
    protected void sendMessage(EMMessage message) {
        if (mute) {
            User currenUser =   UserManager.getCurrentUser();
            if (currenUser.isStudent()){
                ToastUtil.showErrorMsg("当前仅老师可发言");
                return;
            }
        }
        super.sendMessage(message);
    }






    protected void muteStateChanged(boolean muteState){
        mute = muteState;
    }


}
